/*
Copyright (C) 2022-2024 Inspur Corp. All Rights Reserved.

SPDX-License-Identifier: Apache-2.0
*/
package controller

import (
	"did-service/auth"
	"did-service/bean/param"
	"did-service/common/constant"
	"did-service/common/http"
	"strconv"

	"github.com/emicklei/go-restful"
)

// CreateCpt 创建,修改CPT
func (dc *DidController) OperationCpt(req *restful.Request, resp *restful.Response) {
	var cptParam param.DidCPTParam
	if err := req.ReadEntity(&cptParam); err != nil {
		log.Errorf("read entity error: %v", err)
		http.Failed(resp, "cpt参数错误!")
		return
	}
	if cptParam.Operation == "" {
		http.Failed(resp, "请求参数不合法！")
		return
	}
	walletId := auth.GetCurrentWalletId(req)
	cptParam.WalletId = walletId
	if cptParam.Operation == "create" {

		cpt, err2 := dc.srv.CreateCpt(&cptParam)
		if err2 != nil {
			log.Errorf("create cpt error: %v", err2)
			http.Failed(resp, err2.Error())
			return
		}
		http.OkWithData(resp, "创建成功", cpt)
	}
	if cptParam.Operation == "edit" {
		if cptParam.CptId == "" {
			http.Failed(resp, "cptId不能为空！")
			return
		}
		userType := auth.GetCurrentUserType(req)
		if userType == constant.UserTypeIssuer {
			info, issuerInfoErr := dc.srv.GetIssuerInfo(cptParam.CptId, walletId)
			if issuerInfoErr != nil {
				log.Errorf("查询失败: %v", issuerInfoErr)
				http.Failed(resp, issuerInfoErr.Error())
				return
			}
			if info.CptIssuerId != info.IssuerId {
				http.Failed(resp, "当前用户与发证方不对应!")
				return
			}
		}

		cpt, err2 := dc.srv.EditCpt(&cptParam)
		if err2 != nil {
			log.Errorf("edit cpt error: %v", err2)
			http.Failed(resp, err2.Error())
			return
		}
		http.OkWithData(resp, "修改成功", cpt)
	}

}

func (dc *DidController) CreateCpt(req *restful.Request, resp *restful.Response) {
	var cptParam param.DidCPTParam
	if err := req.ReadEntity(&cptParam); err != nil {
		log.Errorf("read entity error: %v", err)
		http.Failed(resp, "cpt参数错误!")
		return
	}
	walletId := auth.GetCurrentWalletId(req)
	cptParam.WalletId = walletId

	properties := cptParam.CptJsonSchema.Properties
	counts := make(map[string]int)
	for _, pro := range properties {
		if _, ok := counts[pro.Property]; ok {
			counts[pro.Property]++
		} else {
			counts[pro.Property] = 1
		}
	}

	for _, count := range counts {
		if count > 1 {
			http.Failed(resp, "属性名不能重复!")
			return
		}
	}
	result, err := dc.srv.CreateCpt(&cptParam)
	if err != nil {
		log.Errorf("create cpt error: %v", err)
		http.Failed(resp, "创建失败")
		return
	}
	http.OkWithData(resp, "创建成功", result)
}

func (dc *DidController) UpdateCpt(req *restful.Request, resp *restful.Response) {
	cptId := req.PathParameter("cptId")
	var cptParam param.DidCPTParam
	if err := req.ReadEntity(&cptParam); err != nil {
		log.Errorf("read entity error: %v", err)
		http.Failed(resp, "cpt参数错误!")
		return
	}
	userType := auth.GetCurrentUserType(req)
	walletId := auth.GetCurrentWalletId(req)
	if userType == constant.UserTypeIssuer {
		info, issuerInfoErr := dc.srv.GetIssuerInfo(cptId, walletId)
		if issuerInfoErr != nil {
			log.Errorf("查询失败: %v", issuerInfoErr)
			http.Failed(resp, issuerInfoErr.Error())
			return
		}
		if info.CptIssuerId != info.IssuerId {
			http.Failed(resp, "当前用户与发证方不对应!")
			return
		}
	}
	cptParam.CptId = cptId
	cptParam.WalletId = walletId
	result, err := dc.srv.EditCpt(&cptParam)
	if err != nil {
		log.Errorf("create cpt error: %v", err)
		http.Failed(resp, "修改失败")
		return
	}
	if result == nil {
		http.Failed(resp, "CPT不存在")
		return
	}
	http.OkWithData(resp, "修改成功", result)
}

// GetCpt 获取CPT详情
func (dc *DidController) GetCpt(req *restful.Request, resp *restful.Response) {
	cptId := req.PathParameter("cptId")
	if cptId == "" {
		log.Error("cptId is empty!")
		http.Failed(resp, "请求参数不合法")
		return
	}

	cptResult, err := dc.srv.GetCpt(cptId)
	if err != nil {
		log.Errorf("查询失败: %v", err)
		http.Failed(resp, err.Error())
		return
	}

	http.OkWithData(resp, "查询成功", cptResult)
}

// ListCptPage 获取CPT列表分页
func (dc *DidController) ListCptPage(req *restful.Request, resp *restful.Response) {
	strPageSize := req.QueryParameter("pageSize")
	strPageNo := req.QueryParameter("pageNum")
	title := req.QueryParameter("title")
	status := req.QueryParameter("status")
	issuerName := req.QueryParameter("issuerName")
	walletId := auth.GetCurrentWalletId(req)
	userType := auth.GetCurrentUserType(req)
	pageNo := 1
	pageSize := 5
	if strPageNo != "" {
		pageNo, _ = strconv.Atoi(strPageNo)
	}

	if strPageSize != "" {
		pageSize, _ = strconv.Atoi(strPageSize)
	}

	page := dc.srv.ListCptPage(pageSize, pageNo, title, walletId, userType, status, issuerName)
	http.OkWithData(resp, "查询成功", page)
}

// GetCptEnum 获取CPT下拉列表
func (dc *DidController) GetCptEnum(req *restful.Request, resp *restful.Response) {
	publisherId := req.QueryParameter("publisherId")
	if publisherId == "" {
		log.Error("publisherId is empty!")
		http.Failed(resp, "请求参数不合法")
		return
	}
	enum, err := dc.srv.GetCptEnum(publisherId)
	if err != nil {
		log.Errorf("查询失败: %v", err)
		http.Failed(resp, err.Error())
		return
	}
	http.OkWithData(resp, "查询成功", enum)
}

// ListCptProperty 获取凭证属性
func (dc *DidController) ListCptProperty(req *restful.Request, resp *restful.Response) {
	cptId := req.QueryParameter("cptId")
	if cptId == "" {
		log.Error("cptId is empty!")
		http.Failed(resp, "请求参数不合法")
		return
	}
	property, err := dc.srv.ListCptProperty(cptId)
	if err != nil {
		log.Errorf("查询失败: %v", err)
		http.Failed(resp, err.Error())
		return
	}
	http.OkWithData(resp, "查询成功", property)
}

// EditStatus 审核cpt
func (dc *DidController) EditStatus(req *restful.Request, resp *restful.Response) {
	var cptParam param.EditCPTStatusParam
	if err := req.ReadEntity(&cptParam); err != nil {
		log.Errorf("read entity error: %v", err)
		http.Failed(resp, "cpt参数错误!")
		return
	}
	if cptParam.CptId == "" {
		http.Failed(resp, "cpt参数错误!")
		return
	}
	userType := auth.GetCurrentUserType(req)
	if userType != constant.UserTypeAdmin {
		http.Failed(resp, "登录用户错误")
		return
	}
	err := dc.srv.EditStatus(cptParam.CptId, cptParam.Status)
	if err != nil {
		log.Errorf("修改失败: %v", err)
		http.Failed(resp, "修改失败")
		return
	}
	http.Ok(resp, "修改成功")
}
